# coding: utf-8

from util import udpSocketClient, logging, sysEncode, BUF_SIZE

ADDR = ('127.0.0.1', 10021)       #服务器端地址

def saveData(sock):
	"""

	保存文件
	"""
	count = 0
	fileSize = 1
	fileName = 'test'
	downloadSize = 0
	while True:
		if count == 0:
			sock.sendto('hello', ADDR)

		recvdata, addr = sock.recvfrom(BUF_SIZE)
		if recvdata == 'end':
			break
		elif '<fileName>:' in recvdata:
			fileName = 'copy_' + recvdata.split('<fileName>:')[1]
			logging.info(sysEncode('开始下载文件: `%s`, 保存文件名: `%s`' % (recvdata.split('<fileName>:')[1], fileName)))
		elif '<fileSize>:' in recvdata:
			fileSize = int(recvdata.split('<fileSize>:')[1])
		elif recvdata:
			with open(fileName, 'ab') as f:
				f.write(recvdata)
			downloadSize += len(recvdata)
			Progress = (downloadSize*100)/fileSize
			chunk = '▇'*(Progress/10)
			downloadProgress = '%s%s' % (Progress, '%')
			logging.info(sysEncode('下载进度: %s %s' % (chunk, downloadProgress)))
		count += 1
	logging.info(sysEncode('下载结束...'))
	
	
def main():
	sock = udpSocketClient()
	
	saveData(sock)

	sock.close()

if __name__ == '__main__':
	main()